<template>
  <el-form
      label-position="left"
      label-width="100px"
      :model="publish"
  >
    <el-form-item label="标题">
      <el-input type="text" v-model="publish.title"></el-input>
    </el-form-item>
    <el-form-item label="描述">
      <el-input type="textarea" v-model="publish.description"></el-input>
    </el-form-item>
    <el-form-item label="分类">
      <el-select v-model="publish.categoryIds" multiple placeholder="分类">
        <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
        >
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="开放">
      <el-radio v-model="publish.isPrivate" :label="false">是</el-radio>
      <el-radio v-model="publish.isPrivate" :label="true">否</el-radio>
    </el-form-item>
    <el-form-item>
      <small style="color: lightcoral">*若要生成目录则点击标题选择H1</small>
    </el-form-item>

    <el-form-item label="内容">
      <editor @publishContent="changeContent"></editor>
    </el-form-item>
    <el-form-item :style="{'text-align':'right'}">
      <el-button type="primary" @click.prevent="publishArticle">发布</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { defineComponent, reactive, onMounted } from 'vue'
import Editor from './Editor'
import { getCategoryList } from '@/api/category'
import { createArticle } from '@/api/article'
import { ElMessage } from 'element-plus'

export default defineComponent({
  name: 'Publish',
  components: { Editor },
  setup () {
    const publish = reactive({
      content: '',
      title: '',
      categoryIds: [],
      description: '',
      isPrivate: false
    })
    const categoryList = reactive([])
    const initCategoryList = async () => {
      const reply = await getCategoryList()
      categoryList.length = 0
      if (reply.data.code === 0) {
        reply.data.data.list.forEach((item) => {
          categoryList.push(item)
        })
      }
    }
    const publishArticle = async () => {
      const reply = await createArticle({
        isPrivate: publish.isPrivate,
        title: publish.title,
        description: publish.description,
        categoryIds: publish.categoryIds,
        content: publish.content
      })
      if (reply.data.code === 0) {
        ElMessage({
          message: '发布成功',
          type: 'success',
          offset: 90,
          duration: 1500
        })
        return
      }
      ElMessage({
        message: reply.data.msg,
        type: 'error',
        offset: 90,
        duration: 1500
      })
    }

    const changeContent = (data) => {
      publish.content = data
    }

    onMounted(() => {
      initCategoryList()
    })
    return {
      changeContent,
      publish,
      categoryList,
      publishArticle
    }
  }
})
</script>

<style scoped>

</style>
